//
//  HomePageViewController.m
//  DaleTou
//
//  Created by hejingjin on 2018/5/27.
//  Copyright © 2018年 geren. All rights reserved.
//

#import "HomePageViewController.h"
#import "Appearance.h"
#import "HomeSectionTwoCollectionHeader.h"
#import "HomeSectionThreeCollectionHeader.h"
#import "HomeSecetionCollectionViewCell.h"
#import "HomeSectionOtherCell.h"
#import "LotteryPredictVC.h"
#import "ShakeVC.h"
#import "HomeMasterCollectionCell.h"
#import "MasterListViewController.h"
#import "MJExtension.h"
#import "HomeSectionOneCollectionViewCell.h"

#import "BetSkillVC.h"
#import "NumberDNAVC.h"
#import "BonusCalculatorVC.h"
#import "DaletouViewController.h"
#import "DaleTouModel.h"
#import "OrderSquareVC.h"
#import "zhoushiViewController.h"

#import "NetWorkManager.h"
#import "MasterViewController.h"
#import "DLTModel.h"
#import "MQRequestTools.h"

@interface HomePageViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong) UICollectionView *collectionview;
@property(nonatomic,strong)NSMutableArray *itemList;
@property(nonatomic,strong)NSArray *imagenamearray;
@property(nonatomic,strong)NSArray *titleArray;
@property(nonatomic,strong)NSArray *subtitleArray;
@property(nonatomic,strong)NSArray *masterList;
@property(nonatomic,strong)NSArray *allMasterList;
@property(nonatomic,assign)NSInteger currentindex;
@property(nonatomic,strong)NSMutableArray *readarray;
@property(nonatomic,strong)NSMutableArray *bluearray;
@property(nonatomic,strong)NSArray *openList;

@property(nonatomic,strong)NSMutableArray *dataSource;



@end

@implementation HomePageViewController

-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

-(NSMutableArray *)readarray{
    if (!_readarray) {
        _readarray = [NSMutableArray array];
    }
    return _readarray;
}

-(NSMutableArray *)bluearray{
    if (!_bluearray) {
        _bluearray = [NSMutableArray array];
    }
    return _bluearray;
}

-(void)reloadNumber{
    
    NSMutableArray *readArray = [NSMutableArray array];
    NSMutableArray *blueArray = [NSMutableArray array];
    while (readArray.count<5) {
        int x = arc4random()%35 +1;
        NSNumber *number = [NSNumber numberWithInteger:x];
        if (![readArray containsObject:number]) {
            [readArray addObject:number];
        }
        
    }
    while (blueArray.count<2) {
        int x = arc4random()%12 +1;
        NSNumber *number = [NSNumber numberWithInteger:x];
        if (![blueArray containsObject:number]) {
            [blueArray addObject:number];
        }
    }
    self.readarray = [readArray mutableCopy];
    self.bluearray = [blueArray mutableCopy];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"ffffff"];
    [self setNavConfigStartColor:@"#F57321" endColor:@"#F57321"];
    [self ApptitileView:@"首页"];
    self.currentindex = 0;
    [self reloadNumber];
    [self requestOpenData];
    _imagenamearray = @[@"投注预测",@"幸运摇号",@"晒单广场",@"投注技巧",@"号码DNA",@"号码走势",@"奖金计算器"];
    _titleArray = @[@"",@"",@"",@"投注技巧",@"号码DNA",@"购彩流程",@"奖金计算器"];
    _subtitleArray = @[@"",@"",@"",@"轻松玩转大乐透",@"号码的前世今生",@"实体店打票",@"方便快捷准确"];
    _allMasterList = [MasterModel mj_objectArrayWithFilename:@"masterList.plist"];
    _masterList = _allMasterList[0];
    
 
    
    [self.view addSubview:self.collectionview];
    [self.collectionview reloadData];
    
    MQRequestTools *tools = [MQRequestTools sharedInstance];
    [tools.sessionManager POST:@"https://api.api68.com/QuanGuoCai/getHistoryLotteryInfo.do?lotCode=10040" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSDictionary *result = [responseObject valueForKey:@"result"];
        NSArray *datearray = [result valueForKey:@"data"];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        //获取完整路径
        NSString *documentsDirectory = [paths objectAtIndex:0];
        
        NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"kaijiang.plist"];//这里就是你将要存储的沙盒路径（.plist文件，名字自定义）
        [datearray writeToFile:plistPath atomically:YES];
        for (NSDictionary *dic in datearray) {
            DaleTouModel *model = [DaleTouModel new];
            model.redarray = [NSMutableArray array];
            model.bluearray = [NSMutableArray array];
            NSString *numberstr = [dic valueForKey:@"preDrawCode"];
            NSString *timestr = [dic valueForKey:@"preDrawTime"];
            NSString *qishu = [dic valueForKey:@"preDrawIssue"];
            model.qishu = qishu;
            model.timestr = [timestr substringWithRange:NSMakeRange(0, 10)];
            NSArray *allnumberarr = [numberstr componentsSeparatedByString:@","];
            if (allnumberarr.count==7) {
                NSArray *readarray = [allnumberarr subarrayWithRange:NSMakeRange(0, 5)];
                NSArray *bulearray = [allnumberarr subarrayWithRange:NSMakeRange(5, 2)];
                for (NSString *str in readarray) {
                    NSNumber *number = [NSNumber numberWithInteger:[str integerValue]];
                    [model.redarray addObject:number];
                }
                for (NSString *str in bulearray) {
                    NSNumber *number = [NSNumber numberWithInteger:[str integerValue]];
                    [model.bluearray addObject:number];
                }
            }
            [self.dataSource addObject:model];
        }
     
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
    }];
    
    
    // Do any additional setup after loading the view.
}

// 获取开奖信息
- (void)requestOpenData {
    // 设置请求参数
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:@"1" forKey:@"pageindex"];
    // 创建url地址
    NSString *urlString = @"http://f.apiplus.net//dlt.json";
    NetWorkManager *manager = [[NetWorkManager alloc] init];
    [manager sendAsynWithURL:urlString parameter:dic success:^(id object) {
        if([object objectForKey:@"data"]){
            _openList = [DLTModel mj_objectArrayWithKeyValuesArray:object[@"data"]];
        }
        // 刷新界面
    } faild:^(id object) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(UICollectionView *)collectionview{
    if (!_collectionview) {
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        flowLayout.minimumInteritemSpacing = 0;
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, NAV_HEIGHT, Main_Screen_Width, Main_Screen_Height - NAV_HEIGHT  - TABBAR_HEIGHT) collectionViewLayout:flowLayout];
        collectionView.showsHorizontalScrollIndicator = NO;
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.backgroundColor = [UIColor colorWithHexString:@"FFFFFF"];
        _collectionview = collectionView;
        _collectionview.delegate = self;
        _collectionview.dataSource = self;
        //        _collectionview.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
        [_collectionview registerNib:[UINib nibWithNibName:@"HomeSecetionCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"HomeSecetionCollectionViewCell"];
        [_collectionview registerNib:[UINib nibWithNibName:@"HomeSectionOneCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"HomeSectionOneCollectionViewCell"];

        
        
        [_collectionview registerNib:[UINib nibWithNibName:@"HomeSectionOtherCell" bundle:nil] forCellWithReuseIdentifier:@"HomeSectionOtherCell"];
        
        [_collectionview registerNib:[UINib nibWithNibName:@"HomeMasterCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"HomeMasterCollectionCell"];
        
        _collectionview.backgroundColor = [UIColor colorWithHexString:@"FFFFFF"];;
        
        
        //defulet头
        UINib *headerhomepagecellNib = [UINib nibWithNibName:NSStringFromClass([HomeSectionTwoCollectionHeader class]) bundle:[NSBundle mainBundle]];
        [_collectionview registerNib:headerhomepagecellNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeSectionTwoCollectionHeader"];
//
//        //defulet头
        UINib *headerhomepagecellNibs = [UINib nibWithNibName:NSStringFromClass([HomeSectionThreeCollectionHeader class]) bundle:[NSBundle mainBundle]];
        [_collectionview registerNib:headerhomepagecellNibs forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeSectionThreeCollectionHeader"];
//        //尾
//        UINib *footerhomepagecellNib = [UINib nibWithNibName:NSStringFromClass([LKCollectionFooterView class]) bundle:[NSBundle mainBundle]];
//        [_collectionview registerNib:footerhomepagecellNib forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"LKCollectionFooterView"];
        
    }
    return _collectionview;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    if (section==0) {
        return 1;
    }else if (section==1){
        return 7;
    }else{
        return 3;
    }
}
//collectionview的Item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size;
    if(indexPath.section==0) {
            size = CGSizeMake(Main_Screen_Width,100);
    }else if(indexPath.section==1){
        if(indexPath.row<=2) {
            size = CGSizeMake(Main_Screen_Width/3,  95);
        }else{
        size = CGSizeMake(Main_Screen_Width/2,  70);
        }

    }else {
        size = CGSizeMake(Main_Screen_Width ,80);
    }

    
    return size;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}



-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section==0) {
            return CGSizeMake(Main_Screen_Width, 0);
    }else if (section==1){
            return CGSizeMake(Main_Screen_Width, 40);
    }else{
            return CGSizeMake(Main_Screen_Width, 95);
    }
 
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{

    return CGSizeMake(Main_Screen_Width, 0);
  
}

//每一个section的间隔
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0,0,0,0);
    
}
    

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
 
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (indexPath.section==1) {
            HomeSectionTwoCollectionHeader *header = (HomeSectionTwoCollectionHeader *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeSectionTwoCollectionHeader" forIndexPath:indexPath];
             return header;
        }else if (indexPath.section ==2){
            HomeSectionThreeCollectionHeader *header1 = (HomeSectionThreeCollectionHeader *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeSectionThreeCollectionHeader" forIndexPath:indexPath];
            
            for (UIButton *btn in header1.btnArray) {
                NSInteger tag = btn.tag;
                btn.layer.cornerRadius = 12.5f;
                btn.layer.masksToBounds = YES;
                if (tag == self.currentindex) {
                    [btn setTitleColor:[UIColor colorWithHexString:@"ffffff"] forState:UIControlStateNormal];
                    [btn setBackgroundColor:[UIColor colorWithHexString:@"F57321"]];
                    btn.layer.borderColor = [UIColor colorWithHexString:@"ffffff"].CGColor;
                    btn.layer.borderWidth = 1.f;
                }else{
                    [btn setTitleColor:[UIColor colorWithHexString:@"333333"] forState:UIControlStateNormal];
                    [btn setBackgroundColor:[UIColor colorWithHexString:@"ffffff"]];
                    btn.layer.borderColor = [UIColor colorWithHexString:@"999999"].CGColor;
                    btn.layer.borderWidth = 1.f;
                }
            }
            [header1 setLookMoreInfo:^{
                MasterListViewController *vc = [[MasterListViewController alloc] init];
                vc.title = @"大师预测";
                vc.masterType = self.currentindex;
                vc.hidesBottomBarWhenPushed = YES;
                vc.openList = self.openList;
                [self.navigationController pushViewController:vc animated:YES];
            }];
            header1.selcetpressed = ^(NSInteger index) {
                if (index !=self.currentindex) {
                    self.currentindex = index;
                    _masterList = _allMasterList[index];
                    [self.collectionview reloadData];
                }
            };
            return header1;
        }else{
                   return [UICollectionReusableView new];
        }
      
        
//
//        if (indexPath.section==1) {
//            return header;
//        }else if(indexPath.section==2){
//            return header1;
//        }else{
//           return [UICollectionReusableView new];
//        }
       
        
    } else if([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        return [UICollectionReusableView new];
    }else{
        return [UICollectionReusableView new];
    }
    
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if ( indexPath.section == 1) {
        if (indexPath.row==0) {
            LotteryPredictVC *VC = [LotteryPredictVC new];
            
            if (self.dataSource.count>0) {
                DaleTouModel *model  = self.dataSource[0];
                VC.model = model;
            }else{
         
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                //获取完整路径
                NSString *documentsDirectory = [paths objectAtIndex:0];
                
                NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"kaijiang.plist"];//这里就是你将要存储的沙盒路径（.plist文件，名字自定义）
                NSMutableArray *datearray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
                if (datearray.count>0) {
                    NSDictionary *dic= datearray.firstObject;
                    DaleTouModel *model = [DaleTouModel new];
                    model.redarray = [NSMutableArray array];
                    model.bluearray = [NSMutableArray array];
                    NSString *numberstr = [dic valueForKey:@"preDrawCode"];
                    NSString *timestr = [dic valueForKey:@"preDrawTime"];
                    NSString *qishu = [dic valueForKey:@"preDrawIssue"];
                    model.qishu = qishu;
                    model.timestr = [timestr substringWithRange:NSMakeRange(0, 10)];
                    NSArray *allnumberarr = [numberstr componentsSeparatedByString:@","];
                    if (allnumberarr.count==7) {
                        NSArray *readarray = [allnumberarr subarrayWithRange:NSMakeRange(0, 5)];
                        NSArray *bulearray = [allnumberarr subarrayWithRange:NSMakeRange(5, 2)];
                        for (NSString *str in readarray) {
                            NSNumber *number = [NSNumber numberWithInteger:[str integerValue]];
                            [model.redarray addObject:number];
                        }
                        for (NSString *str in bulearray) {
                            NSNumber *number = [NSNumber numberWithInteger:[str integerValue]];
                            [model.bluearray addObject:number];
                        }
                    }
                    VC.model = model;
                }
            }
            VC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:VC animated:YES];
        }else if (indexPath.row==1){
            ShakeVC *VC = [ShakeVC new];
            VC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:VC animated:YES];
        }else if (indexPath.row==2){
            OrderSquareVC *VC = [OrderSquareVC new];
            VC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:VC animated:YES];
        }else if (indexPath.row==3){
            BetSkillVC *skill = [[BetSkillVC alloc]init];

             skill.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:skill animated:YES];
        }else if (indexPath.row == 4){
            NumberDNAVC *DNAVC = [[NumberDNAVC alloc]init];
             DNAVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:DNAVC animated:YES];
        }else if (indexPath.row == 5){
            zhoushiViewController *vc = [[zhoushiViewController alloc] init];
             vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 6){
            BonusCalculatorVC *bonusVC = [[BonusCalculatorVC alloc]init];
             bonusVC.hidesBottomBarWhenPushed = YES;

            [self.navigationController pushViewController:bonusVC animated:YES];
        }
        
    } else if ( indexPath.section == 2) {
        MasterViewController *vc = [[MasterViewController alloc] init];
        vc.masterInfo = _masterList[indexPath.row];
        vc.index = self.currentindex;
        vc.pastData = _openList;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section ==0) {

        HomeSectionOneCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeSectionOneCollectionViewCell" forIndexPath:indexPath];
        cell.selcetpressed = ^(NSInteger index) {
            if (index==0) {
                //去投注
                DaletouViewController *vc = [[DaletouViewController alloc] init];
                 vc.hidesBottomBarWhenPushed = YES;
                DaleTouModel *model = [DaleTouModel new];
                model.redarray = [self.readarray mutableCopy];
                model.bluearray = [self.bluearray mutableCopy];
                vc.model = model;
                [self.navigationController pushViewController:vc animated:YES];
                
            }else{
                //重新选
                [self reloadNumber];
                [self.collectionview reloadData];
            }
        };
        for (UIButton *btn in cell.numberBtnArr) {
            NSInteger tag = btn.tag;
            if (tag<5) {
                if (self.readarray.count>tag) {
                    [btn setTitle:[NSString stringWithFormat:@"%@",self.readarray[tag]] forState:UIControlStateNormal];
                }
        
            }else{
                if (self.bluearray.count>tag-5) {
                        [btn setTitle:[NSString stringWithFormat:@"%@",self.bluearray[tag -5]] forState:UIControlStateNormal];
                }
           
            }
            
        }
            return cell;
    }else if (indexPath.section==1){

        if (indexPath.row<=2) {
            HomeSecetionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeSecetionCollectionViewCell" forIndexPath:indexPath];
        
            cell.itemImageview.image = [UIImage imageNamed:_imagenamearray[indexPath.row]];
            return cell;
        }else{
            HomeSectionOtherCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeSectionOtherCell" forIndexPath:indexPath];
            cell.itemImageview.image = [UIImage imageNamed:_imagenamearray[indexPath.row]];
            cell.titleNameLabel.text = _titleArray[indexPath.row];
            cell.subTitleLabel.text = _subtitleArray[indexPath.row];
            return cell;
        }
    }else{
        //大师预测
        HomeMasterCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeMasterCollectionCell" forIndexPath:indexPath];
        cell.index = indexPath.row;
        cell.model = _masterList[indexPath.row];
        return cell;
    }
    

}

- (CGFloat) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
 
    return 0.f;
}


@end
